<?php

/**
*	回帖
*
*/

//包含公共文件
include '../../common/common.php';

//获取post传值
// var_dump($_POST);

$id     = trim($_POST['id']);
$reply = trim($_POST['reply_content']);
$cid    = trim($_POST['cid']);  
$uid    = $_COOKIE['uid'];
// var_dump($uid); 

//获取IP
$ip1 = $_SERVER['REMOTE_ADDR'];
if ('::1') {

	$ip1 = '127.0.0.1';
}
$ip = ip2long($ip1);
// var_dump($ip1);
// var_dump($ip);

//判断是否登录
if (!$_COOKIE['afterlogin']) {

	exit('亲 , 登录后才能发表评论哟 <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
}

//判断帖子是否收费,即rate是否为0
$resCharge  = mySelect($link , '*' , DB_TABLE_DETAIL , "where  id=$id");
$resRate     = $resCharge[0]['rate'];
$authorid    = $resCharge[0]['authorid'];
// var_dump($resCharge);
// var_dump($resRate);

//判断帖子是否收费,若收费则执行
if ($resRate) {

	//查询订单表
	$resOrder  = mySelect($link , '*' , DB_TABLE_ORDER , "where uid=$uid  and  tid=$id");
	// var_dump($resOrder);

	//判断是否有权限回帖 (购买后才能回帖)
	if ($uid != $authorid && !$resOrder) {
		
		exit('请先购买帖子,再进行回复 <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
	}

}

//插入数据库
$data = [
	'first'       => 0 ,
	'tid'	   => $id,
	'classid'   => $cid,
	'content'  => "$reply",
	'addtime'  => time(),
	'addip'	    => $ip,
	'authorid' => $uid
];
// var_dump($data);
$resReply = myInsert($link , DB_TABLE_DETAIL , $data);
// var_dump($resReply);

//得到当前帖子总数, 并将总数更新到帖子的replycount
$currReplyCount = myCount($link , 'id' , DB_TABLE_DETAIL , "where first=0  and  tid=$id ");
$resReplyCount  = myUpdate($link , DB_TABLE_DETAIL , ['replycount' => $currReplyCount ] ,"id=$id");
// var_dump($currReplyCount);
// var_dump($resReplyCount);

//查询用户当前积分和等级
$selGrade = mySelect($link , '*' ,DB_TABLE_USER , "where uid = $uid");
$grade = $selGrade[0]['grade'];
//加积分,并获取响应的等级数
$grade2 = $grade + 5 ; 
$grade3 = myLevel($grade2); 
$levName = $grade3[1];
$border    = $grade3[2];
// var_dump($grade3);
// var_dump($levName);
// var_dump($border);

//修改当前用户积分,等级
$dataLev  =  ['grade' => $grade2 , 'levname' => "$levName"];
$upGrade  = myUpdate($link , DB_TABLE_USER , $dataLev , "uid = $uid");
// var_dump($upGrade);


//判断是否刚升级
if ($grade < $border && $grade2 >= $border) {

	echo '恭喜您升级到<span style="color:red; font-weight:bold;"> ' . $levName . ' </span>';
}



//跳转页面
echo '回复帖子成功, 积分<span style="color:red;">  +5</span>';
header('refresh:1;url=' . $webSite . 'detail.php?id=' . $id);